<template>
    <div class="campaign-dialog">
        <el-dialog v-model="dialogFormVisible" title="添加Campaign" width="620" @close="handleCancel">
            <div style="padding: 10px;">
                <el-form :model="campaignForm" ref="campaignFormRef" :rules="rules" label-width="auto"
                    :disabled="type === 'check'">
                    <el-form-item label="文章ID：" prop="articleId">
                        <el-input v-model="campaignForm.articleId" placeholder="请输入文章ID" @change="handleInputId" />
                    </el-form-item>
                    <el-form-item label="投放渠道：" prop="piSource">
                        <el-select v-model="campaignForm.piSource" placeholder="请选择投放渠道" @change="getCampaignName">
                            <el-option v-for="item in piSourceOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="投放标题：" prop="refTitle">
                        <el-input v-model="campaignForm.refTitle" placeholder="请输入投放标题" />
                    </el-form-item>
                    <el-form-item label="域名：" prop="siteId">
                        <el-select v-model="campaignForm.siteId" placeholder="请选择域名">
                            <el-option v-for="item in siteOptions" :key="item.id" :label="item.siteName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="投放国家地区：" prop="geos">
                        <el-select v-model="campaignForm.geos" placeholder="请选择投放渠道" multiple @change="getCampaignName">
                            <el-option v-for="item in countryOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>

                    </el-form-item>
                    <el-form-item label="PixelId：" prop="ttPixelId">
                        <el-input v-model="campaignForm.ttPixelId" placeholder="请输入PixelId：" />
                    </el-form-item>
                    <el-form-item label="Compaign：" prop="campaignName">
                        <el-input v-model="campaignForm.campaignName" type="textarea" placeholder="请输入Compaign名称" />
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleSubmit(campaignFormRef)" :disabled="type === 'check'">
                        提交
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import service from '../config';
import { countryOptions } from '../tool';
defineComponent({ name: 'CampaignAdd' })
const emit = defineEmits(['getData']);
const dialogFormVisible = ref(false)
const campaignFormRef = ref<FormInstance>()
interface RuleForm {
    articleId: number
    piSource: string
    refTitle: string,
    siteId: number,
    geos: string[],
    campaignName: string,
    ttPixelId: string

}
const campaignForm = ref<RuleForm>({
    articleId: null,
    piSource: '',
    refTitle: '',
    siteId: null,
    geos: [],
    campaignName: '',
    ttPixelId: ''
})
const rules = reactive<FormRules<RuleForm>>({
    articleId: [
        { required: true, message: '请输入文章ID', trigger: 'blur' },
    ],
    piSource: [
        { required: true, message: '请选择投放渠道', trigger: 'blur' },
    ],
    refTitle: [
        { required: true, message: '请输入投放标题', trigger: 'blur' },
    ],
    siteId: [
        { required: true, message: '请选择域名', trigger: 'blur' },
    ],
    campaignName: [{ required: true, message: '请输入Campaign名称', trigger: 'blur' }],
    ttPixelId: [{ required: true, message: '请输入ttPixelId', trigger: 'blur' }]

})
const piSourceOptions = ref([{ label: 'TikTok', value: 'TikTok' }, { label: 'Facebook', value: 'Facebook' }])
const siteOptions = ref([])
const type = ref<string>()
const openModal = (_type?: string, id?: number) => {
    type.value = _type
    dialogFormVisible.value = true
    if (_type === 'add') {
        campaignForm.value.articleId = id
        if (id) {
            setTimeout(() => {
                handleInputId()
            }, 100)
        }
    } else if (_type === 'edit' || _type === 'check') {
        service.post('/campaign/detailById', { id })
            .then(response => {
                campaignForm.value = { ...response?.data, geos: response?.data.geos ? response?.data.geos.split(',') : [] }
                console.log(campaignForm.value);

            })
            .catch(error => {
                ElMessage.error(error?.message)
            });
    }
}
const handleCancel = () => {
    dialogFormVisible.value = false
    campaignForm.value = {
        articleId: null,
        piSource: '',
        refTitle: '',
        siteId: null,
        geos: [],
        campaignName: '',
        ttPixelId: ''
    }
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            service.post(type.value === 'add' ? 'campaign/add' : 'campaign/update', { ...campaignForm.value, geos: campaignForm.value.geos?.join(',') })
                .then(response => {
                    ElMessage.success('提交成功！')
                    dialogFormVisible.value = false
                    campaignForm.value = {
                        articleId: null,
                        piSource: '',
                        refTitle: '',
                        siteId: null,
                        geos: [],
                        campaignName: '',
                        ttPixelId: ''
                    }
                    emit('getData')
                })
                .catch(error => {
                    ElMessage.error(error || '提交失败！')
                });
        } else {

        }
    })
}

const getSite = () => {
    service.get('/site/getAll')
        .then(response => {
            siteOptions.value = response?.data
        })
        .catch(error => {
            ElMessage.error(error)
        });
}


const getCampaignName = () => {
    let geos = ''
    campaignForm.value.geos?.forEach((item, index) => {
        geos += (index === 0 ? '' : '-') + item
    })
    campaignForm.value.campaignName = campaignForm.value.piSource + ((geos && campaignForm.value.piSource) ? '_' : '') + geos
}

const handleInputId = () => {
    service.post('/article/page', { id: Number(campaignForm.value.articleId), pageNum: 1, pageSize: 10 })
        .then(response => {
            campaignForm.value.siteId = response?.data?.records?.[0]?.siteId
        })
        .catch(error => {
        });
}




onMounted(() => {
    getSite()
})
defineExpose({ openModal })
</script>

<style lang="scss">
.campaign-dialog {
    .el-dialog {
        padding: 20px;

        .el-dialog__title {
            font-weight: 700;
        }

        .el-dialog__footer {
            padding: 0;
        }
    }

    .el-form-item {
        margin-bottom: 20px;
    }

    .el-form-item__label {
        font-size: 14px;
        font-weight: 600;
    }
}
</style>